<?php

    /**
     * 创建新的主题自定义项目
     * 快速入门案例
     */
    add_action('customize_register','customize_new_items');
    function customize_new_items($wp_customize){
        
        //创建一个panel
        $wp_customize->add_panel( 'general_panel',array(
            'title'         =>  '主题设置',
            'description'   =>  '主题中允许用户自行设置的内容，都在这里了'
        ));
        
        //创建一个section
        $wp_customize->add_section( 'section_1',array(
            'panel'         =>  'general_panel',
            'title'         =>  '站点SEO',
            'description'   =>  '在这里可以设置站点的基本SEO信息'
        ) );
        
        //创建一个setting
        $wp_customize->add_setting( 'my_site_keywords',array(
            'type'          =>  'theme_mod'
        ));
        
        //创建一个control
        $wp_customize->add_control('control_1',array(
            'section'       =>  'section_1',
            'settings'      =>  'my_site_keywords',
            'label'         =>  '首页关键词'
        ));
        
    }

    /**
     * 注册新的文章类型
     */
	$args = array(
        // 'label' => 'Books',
        'labels'=>[
            'name' => '我的小说',
            'add_new' => '添加小说',
            'add_new_item' => '添加一个新小说',
            'edit' => '编辑',
            'edit_item' => '编辑小说',
            'new_item' => '新小说',
            'view' => '查看',
            'view_item' => '查看小说',
            'search_items' => '搜索小说',
            'not_found' => '没有任何小说',
            'not_found_in_trash' => '没有任何被删除的小说'
        ],
		'public' => true,//可见性
		'description' => '这是新注册的小说类型',
		'menu_position' => 5,//菜单位置
		'supports' => ['title','editor','comments','thumbnail','custom-fields'],//显示那些自定义文章功能'title’,'editor’,'comments’,'revisions’,'trackbacks’,'author’,'excerpt’,'page-attributes’,'thumbnail’,'custom-fields’,'post-formats’
		'singular_label' => 'Books',
		'show_ui' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'rewrite' => false,
		'publicly_queryable' => true,
		'query_var' => true,
		'menu_icon' => 'dashicons-editor-insertmore',
		'has_archive' => true,
		'rewrite' => array("slug" => 'books'),// Permalinks format
	);
    register_post_type( 'Books' ,$args );
    
    register_taxonomy( //书籍类别分类
		'books_type',
		'books',
		array(
			'show_admin_column' => true,
			'rewrite' => array(
				'slug' => 'books_type'
            ),
            'show_ui' => true,
            'show_in_nav_menus'		=>	true,
            'hierarchical'						=>	true
		)
    );
    register_taxonomy( //书籍作者分类
		'books_author',
        'books',
		array(
			'show_admin_column' => true,
			'rewrite' => array(
				'slug' => 'books_author'
            ),
            'show_ui' => true,
            'show_in_nav_menus'		=>	true,
            'hierarchical'=>	false,
            'labels'=>[
                'name' => '作者',
            ],
		)
	);
    /**
     * 为后台创建菜单与子菜单
     */
    add_action('admin_menu','yw_create_menu');
    function yw_create_menu(){
        add_menu_page( //创建插件顶级菜单
            '书城的插件首页',
            '书城的插件',
            'manage_options',//权限
            'yw_books_menu',//唯一的名字标识s
            'yw_books_menu_page',//调用显示页面的方法
            get_template_directory_uri().'/Images/icon.png'
        );
        add_submenu_page(
            'yw_books_menu',//父菜单的别名
            '关于书城的插件',// title的内容
            '关于',//栏目名字
            'manage_options',//权限
            'yw_books_submenu',//唯一的名字标识s
            'yw_books_submenu_page'//调用显示页面的方法
        );
    }
    function yw_books_menu_page(){ //这是上面的显示页面的方法
        // echo get_template_directory_uri().'/Images/icon.png';
        echo '<h1>这是一个标题</h1>';
    }
    function yw_books_submenu_page(){
        echo '<h1>这个插件是个学习的插件</h1>';
    }

    add_post_type_support( 'page',array( 'excerpt' ) ); //给页面管理添加摘要的功能

    /**
    * getPostViews()函数
    * 功能：获取阅读数量
    * 在需要显示浏览次数的位置，调用此函数
    * @Param object|int $postID   文章的id
    * @Return string $count		  文章阅读数量
    */
    function getPostViews( $postID ) {
        $count_key = 'post_views_count';
        $count = get_post_meta( $postID,$count_key,true );
        if( $count=='' ) {
            delete_post_meta( $postID,$count_key );
            add_post_meta( $postID,$count_key,'0' );
            return "0";
        }
    return $count;
    }

    /**
     * 添加元数据框
     */
   add_action('add_meta_boxes','books_meta_boxes'); //在挂钩上挂载一个元数据框方法
    function books_meta_boxes(){
        $screens=['books'];
        add_meta_box(
            'yw_books_metabox',
            '转载自',
            'books_meta_boxes_callback',//回调函数
            $screens,
            'side' //显示位置，文章编辑页面包括’normal’,'side’,and 'advanced’的形式
        );
    }
    function books_meta_boxes_callback($post){ //元数据框展示代码
        wp_nonce_field('yw_books_meta_boxes_data','yw_books_meta_boxes_nonce'); //添加一个验证信息，这个在保存元数据的时候用到
        /*
	 * 输出元数据信息
	 */
	$value = get_post_meta( $post->ID,'_zzurl',true );

	echo '<label for="myplugin_new_field">'; //输出元数据框
	_e( '本文章转载自：' );
	echo '</label> ';
	echo '<input type="text" id="_zzurl" name="_zzurl" value="' . esc_attr( $value ) . '" size="25" />';
    }

    //文章保存的时候，会调用 save_post 钩子，因此我们要借助这个钩子来保存元数据框内的数据
    add_action( 'save_post','yw_books_meta_boxes_data' );
    
    function yw_books_meta_boxes_data( $post_id ) {
	
        //验证是否为有效信息
        if ( ! isset( $_POST['yw_books_meta_boxes_nonce'] ) ) {
            return;
        }
        
        if ( ! wp_verify_nonce( $_POST['yw_books_meta_boxes_nonce'],'yw_books_meta_boxes_data' ) ) {
            return;
        }
    
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
    
        // Check the user's permissions.
        if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
    
            if ( ! current_user_can( 'edit_page',$post_id ) ) {
                return;
            }
    
        } else {
    
            if ( ! current_user_can( 'edit_post',$post_id ) ) {
                return;
            }
        }
    
        if ( ! isset( $_POST['_zzurl'] ) ) {
            return;
        }
    
        $my_data = sanitize_text_field( $_POST['_zzurl'] );
    
        update_post_meta( $post_id,'_zzurl',$my_data );
    }
    

    /**
    * setPostViews()函数  
    * 功能：设置或更新阅读数量
    * 在内容页(single.php，或page.php )调用此函数
    * @Param object|int $postID   文章的id
    * @Return string $count		  文章阅读数量
    */
    function setPostViews( $postID ) {
        $count_key = 'post_views_count';
        $count = get_post_meta( $postID,$count_key,true );
        if( $count=='' ) {
            $count = 0;
            delete_post_meta( $postID,$count_key );
            add_post_meta( $postID,$count_key,'0' );
        } else {
            $count++;
            update_post_meta( $postID,$count_key,$count );
        }
    }
    /*
    register_sidebar( $args )
    函数功能：开启侧边栏功能
    @参数 array $args，参数是一个数组，包含多个成员参数。
    所有可选的成员参数，都包含在下面的示例代码中。
    */
    register_sidebar( array(
        'name'						=> '主侧边栏',					//侧边栏的名称
        'id'								=> 'sidebar-1',					//侧边栏的编号
        'description'				=> '用于网站右侧的主侧边栏',					//侧边栏的描述
        'class'						=> '',
        'before_widget'			=> '<li id="%1$s" class="widget %2$s">',
        'after_widget'			=> '</li>',
        'before_title'				=> '<h3 class="widget-title">',
        'after_title'					=> '</h3>' 
    ) );
    /**格式化站点title */
    add_filter('wp_title','yw_wp_head',10,3);
    function yw_wp_head($title,$sep,$seplocation ){
        global $paged,$page;
        if(is_feed()){
            return $title;
        }

        $title.=get_bloginfo('name').'-'; //获取站点名称
        $title.=get_bloginfo('description','display');

        if($paged>=2 || $page>=2){
            $title.=printf('第%s页',max($paged,$page));
        }

        $search = array('&#8211;',' '); //去除空格，-的字符实体
        $replace = array('-','');
        $title = str_replace($search,$replace,$title);
        return $title;
    }

    /**添加功能 */

    add_theme_support('post-thumbnails'); //缩略图功能

    add_theme_support('automatic-feed-links'); //添加feed功能

    add_action('after_setup_theme','yw_set_up');
    function yw_set_up(){ 
        add_theme_support('custom-logo',[ //开启自定义logo功能
            'height'=>250,
            'weight'=>250,
            'flex-weight'=>true,
            'flex-height'=>true,
        ]);
        add_theme_support('custom-header');
    }

    /**加载样式 js文件 */
    add_action('wp_enqueue_scripts','yw_enqueue_scriptions');
    function yw_enqueue_scriptions(){ //加载资源文件
        // wp_enqueue_style('blog_style',get_stylesheet_uri()); //加载style.css 样式
        wp_enqueue_style('books_style',get_template_directory_uri() . '/Css/bijuge.css'); //加载style.css 样式
        wp_enqueue_script( 'books_jquery',get_template_directory_uri() . '/Scripts/jquery.min.js',array(),'20151215',false );
        // wp_enqueue_script( 'books_bqg',get_template_directory_uri() . '/Scripts/bqg.js',array('books_jquery'),'20151215',true );
    }

    /** 注册导航*/
    register_nav_menu('yw-main','主导航');
    register_nav_menu('yw-foot','底部导航');

    /**
    * lingfeng_breadcrumbs()函数
    * 功能是输出面包屑导航HTML代码
    * @Param null			不需要输入任何参数
    * @Return string		输出HTML代码
    */
    function lingfeng_breadcrumbs() {
        /* === OPTIONS === */
        $text['home']     = '网站首页'; // text for the 'Home' link
        $text['category'] = '%s'; // text for a category page
        $text['search']   = '"%s"的搜索结果'; // text for a search results page
        $text['tag']      = '%s'; // text for a tag page
        $text['author']   = '%s'; // text for an author page
        $text['404']      = '404错误'; // text for the 404 page

        $show_current   = 1; // 1 - show current post/page/category title in breadcrumbs,0 - don't show
        $show_on_home   = 1; // 1 - show breadcrumbs on the homepage,0 - don't show
        $show_home_link = 1; // 1 - show the 'Home' link,0 - don't show
        $show_title     = 1; // 1 - show the title for the links,0 - don't show
        $delimiter      = ' &raquo; '; // delimiter between crumbs
        $before         = '<span class="current">'; // tag before the current crumb
        $after          = '</span>'; // tag after the current crumb
        /* === END OF OPTIONS === */

        global $post;
        $home_link    = home_url('/');
        $link_before  = '<span typeof="v:Breadcrumb">';
        $link_after   = '</span>';
        $link_attr    = ' rel="v:url" property="v:title"';
        $link         = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
        $parent_id    = $parent_id_2 = $post->post_parent;
        $frontpage_id = get_option('page_on_front');

        if (is_home() || is_front_page()) {

            if ($show_on_home == 1) echo '<div class="breadcrumbs"><a href="' . $home_link . '">' . $text['home'] . '</a></div>';

        } else {

            echo '<div class="breadcrumbs" xmlns:v="http://rdf.data-vocabulary.org/#">';
            if ($show_home_link == 1) {
                echo '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $text['home'] . '</a>';
                if ($frontpage_id == 0 || $parent_id != $frontpage_id) echo $delimiter;
            }

            if ( is_category() ) {
                $this_cat = get_category(get_query_var('cat'),false);
                if ($this_cat->parent != 0) {
                    $cats = get_category_parents($this_cat->parent,TRUE,$delimiter);
                    if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#","$1",$cats);
                    $cats = str_replace('<a',$link_before . '<a' . $link_attr,$cats);
                    $cats = str_replace('</a>','</a>' . $link_after,$cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/','',$cats);
                    echo $cats;
                }
                if ($show_current == 1) echo $before . sprintf($text['category'],single_cat_title('',false)) . $after;

            } elseif ( is_search() ) {
                echo $before . sprintf($text['search'],get_search_query()) . $after;

            } elseif ( is_day() ) {
                echo sprintf($link,get_year_link(get_the_time('Y')),get_the_time('Y')) . $delimiter;
                echo sprintf($link,get_month_link(get_the_time('Y'),get_the_time('m')),get_the_time('F')) . $delimiter;
                echo $before . get_the_time('d') . $after;

            } elseif ( is_month() ) {
                echo sprintf($link,get_year_link(get_the_time('Y')),get_the_time('Y')) . $delimiter;
                echo $before . get_the_time('F') . $after;

            } elseif ( is_year() ) {
                echo $before . get_the_time('Y') . $after;

            } elseif ( is_single() && !is_attachment() ) {
                if ( get_post_type() != 'post' ) {
                    $post_type = get_post_type_object(get_post_type());
                    $slug = $post_type->rewrite;
                    printf($link,$home_link . $slug['slug'] . '/',$post_type->labels->singular_name);
                    if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;
                } else {
                    $cat = get_the_category(); $cat = $cat[0];
                    $cats = get_category_parents($cat,TRUE,$delimiter);
                    if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#","$1",$cats);
                    $cats = str_replace('<a',$link_before . '<a' . $link_attr,$cats);
                    $cats = str_replace('</a>','</a>' . $link_after,$cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/','',$cats);
                    echo $cats;
                    if ($show_current == 1) echo $before . get_the_title() . $after;
                }

            } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
                $post_type = get_post_type_object(get_post_type());
                echo $before . $post_type->labels->singular_name . $after;

            } elseif ( is_attachment() ) {
                $parent = get_post($parent_id);
                $cat = get_the_category($parent->ID); $cat = $cat[0];
                if ($cat) {
                    $cats = get_category_parents($cat,TRUE,$delimiter);
                    $cats = str_replace('<a',$link_before . '<a' . $link_attr,$cats);
                    $cats = str_replace('</a>','</a>' . $link_after,$cats);
                    if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/','',$cats);
                    echo $cats;
                }
                printf($link,get_permalink($parent),$parent->post_title);
                if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after;

            } elseif ( is_page() && !$parent_id ) {
                if ($show_current == 1) echo $before . get_the_title() . $after;

            } elseif ( is_page() && $parent_id ) {
                if ($parent_id != $frontpage_id) {
                    $breadcrumbs = array();
                    while ($parent_id) {
                        $page = get_page($parent_id);
                        if ($parent_id != $frontpage_id) {
                            $breadcrumbs[] = sprintf($link,get_permalink($page->ID),get_the_title($page->ID));
                        }
                        $parent_id = $page->post_parent;
                    }
                    $breadcrumbs = array_reverse($breadcrumbs);
                    for ($i = 0; $i < count($breadcrumbs); $i++) {
                        echo $breadcrumbs[$i];
                        if ($i != count($breadcrumbs)-1) echo $delimiter;
                    }
                }
                if ($show_current == 1) {
                    if ($show_home_link == 1 || ($parent_id_2 != 0 && $parent_id_2 != $frontpage_id)) echo $delimiter;
                    echo $before . get_the_title() . $after;
                }

            } elseif ( is_tag() ) {
                echo $before . sprintf($text['tag'],single_tag_title('',false)) . $after;

            } elseif ( is_author() ) {
                global $author;
                $userdata = get_userdata($author);
                echo $before . sprintf($text['author'],$userdata->display_name) . $after;

            } elseif ( is_404() ) {
                echo $before . $text['404'] . $after;

            } elseif ( has_post_format() && !is_singular() ) {
                echo get_post_format_string( get_post_format() );
            }

            if ( get_query_var('paged') ) {
                if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
                echo __('Page') . ' ' . get_query_var('paged');
                if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
            }

            echo '</div><!-- .breadcrumbs -->';

        }
    } // end dimox_breadcrumbs()
    /**
    * lingfeng_strimwidth( ) 函数
    * 功能：字符串截取，并去除字符串中的html和php标签
    * @Param string $str			要截取的原始字符串
    * @Param int $len				截取的长度
    * @Param string $suffix		字符串结尾的标识
    * @Return string					处理后的字符串
    */
    function lingfeng_strimwidth( $str,$len,$start = 0,$suffix = '……' ) {
        $str = str_replace(array(' ','　','&nbsp;','\r\n'),'',strip_tags( $str ));
        if ( $len>mb_strlen( $str ) ) {
            return mb_substr( $str,$start,$len );
        }
        return mb_substr($str,$start,$len) . $suffix;
    }

    /**
    * 数字分页函数
    * 因为wordpress默认仅仅提供简单分页
    * 所以要实现数字分页，需要自定义函数
    * @Param int $range			数字分页的宽度
    * @Return string|empty		输出分页的HTML代码		
    */
    function lingfeng_pagenavi( $range = 4 ) {
        global $paged,$wp_query;
        if ( !$max_page ) {
            $max_page = $wp_query->max_num_pages;
        }
        if( $max_page >1 ) {
            echo "<div class='fenye'>"; 
            if( !$paged ){
                $paged = 1;
            }
            if( $paged != 1 ) {
                echo "<a href='".get_pagenum_link(1) ."' class='extend' title='跳转到首页'>首页</a>";
            }
            previous_posts_link('上一页');
            if ( $max_page >$range ) {
                if( $paged <$range ) {
                    for( $i = 1; $i <= ($range +1); $i++ ) {
                        echo "<a href='".get_pagenum_link($i) ."'";
                    if($i==$paged) echo " class='current'";echo ">$i</a>";
                    }
                }elseif($paged >= ($max_page -ceil(($range/2)))){
                    for($i = $max_page -$range;$i <= $max_page;$i++){
                        echo "<a href='".get_pagenum_link($i) ."'";
                        if($i==$paged)echo " class='current'";echo ">$i</a>";
                        }
                    }elseif($paged >= $range &&$paged <($max_page -ceil(($range/2)))){
                        for($i = ($paged -ceil($range/2));$i <= ($paged +ceil(($range/2)));$i++){
                            echo "<a href='".get_pagenum_link($i) ."'";if($i==$paged) echo " class='current'";echo ">$i</a>";
                        }
                    }
                }else{
                    for($i = 1;$i <= $max_page;$i++){
                        echo "<a href='".get_pagenum_link($i) ."'";
                        if($i==$paged)echo " class='current'";echo ">$i</a>";
                    }
                }
            next_posts_link('下一页');
            if($paged != $max_page){
                echo "<a href='".get_pagenum_link($max_page) ."' class='extend' title='跳转到最后一页'>尾页</a>";
            }
            echo '<span>共['.$max_page.']页</span>';
            echo "</div>\n";  
        }
    }


    //自定义评论列表模板
    function simple_comment($comment,$args,$depth) {
        $GLOBALS['comment'] = $comment; ?>
        <li class="comment" id="li-comment-<?php comment_ID(); ?>">
                <div class="media">
                    <div class="media-left">
                    <?php if (function_exists('get_avatar') && get_option('show_avatars')) { echo get_avatar($comment,48); } ?>
                    </div>
                    <div class="media-body">
                        <?php printf(__('<p class="author_name">%s</p>'),get_comment_author_link()); ?>
                    <?php if ($comment->comment_approved == '0') : ?>
                        <em>评论等待审核...</em><br />
                    <?php endif; ?>
                    <?php comment_text(); ?>
                    </div>
                </div>
                <div class="comment-metadata">
                    <span class="comment-pub-time">
                        <?php echo get_comment_time('Y-m-d H:i'); ?>
                    </span>
                    <span class="comment-btn-reply">
                    <i class="fa fa-reply"></i> <?php comment_reply_link(array_merge( $args,array('reply_text' => '回复','depth' => $depth,'max_depth' => $args['max_depth']))) ?> 
                    </span>
                </div>
    
    <?php
    }

    /** 小说章节添加成功后，更新小说内容*/
    add_action('save_post','update_books_mess',10,3);
    function update_books_mess(int $post_ID, WP_Post $post, bool $update){
        // Only set for post_type = post!
        if ( 'post' !== $post->post_type ) {
            return;
        }

        $post_title=$post->post_title;
        // $post_link=$post->permalink;

        $cates=get_the_category($post_ID); //获取自定义类别名称
        $cate=$cates[0]->name;

        $my_query=new WP_query(['name'=>$cate]);
        if($my_query->have_posts()){
            while($my_query->have_posts()){
                $my_query->the_post();
                add_post_meta(get_the_ID(),'latest_title','aaaaaaa');
                // add_post_meta(get_the_ID(),'latest_link',$post_);
            }
        }
        wp_reset_postdata();

    }